import CryptoJS from 'crypto-js'

class CryptoUtil {
  // AES加密密钥（实际项目中应该从环境变量获取）
  static SECRET_KEY = 'moolio_secret_key_2024'

  // AES加密
  static encrypt(data) {
    if (typeof data === 'object') {
      data = JSON.stringify(data)
    }
    return CryptoJS.AES.encrypt(data, this.SECRET_KEY).toString()
  }

  // AES解密
  static decrypt(encryptedData) {
    try {
      const bytes = CryptoJS.AES.decrypt(encryptedData, this.SECRET_KEY)
      const decrypted = bytes.toString(CryptoJS.enc.Utf8)
      try {
        return JSON.parse(decrypted)
      } catch {
        return decrypted
      }
    } catch (error) {
      console.error('解密失败:', error)
      return null
    }
  }

  // MD5加密
  static md5(data) {
    return CryptoJS.MD5(data).toString()
  }

  // SHA256加密
  static sha256(data) {
    return CryptoJS.SHA256(data).toString()
  }

  // Base64编码
  static base64Encode(data) {
    return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(data))
  }

  // Base64解码
  static base64Decode(data) {
    return CryptoJS.enc.Base64.parse(data).toString(CryptoJS.enc.Utf8)
  }

  // 生成随机字符串
  static randomString(length = 16) {
    const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
    let result = ''
    for (let i = 0; i < length; i++) {
      result += chars.charAt(Math.floor(Math.random() * chars.length))
    }
    return result
  }

  // 生成UUID
  static generateUUID() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
      const r = Math.random() * 16 | 0
      const v = c === 'x' ? r : (r & 0x3 | 0x8)
      return v.toString(16)
    })
  }

  // 密码哈希（用于用户密码存储）
  static hashPassword(password, salt = null) {
    if (!salt) {
      salt = this.randomString(16)
    }
    const hashedPassword = this.sha256(password + salt)
    return {
      hash: hashedPassword,
      salt: salt
    }
  }

  // 验证密码
  static verifyPassword(password, hash, salt) {
    const hashedPassword = this.sha256(password + salt)
    return hashedPassword === hash
  }
}

export default CryptoUtil 